package com.sky.sky_server.controller;

import java.util.Map;

import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.sky.sky_common.constant.JwtRoleConstant;
import com.sky.sky_common.exception.EmployeeLoginException;
import com.sky.sky_common.util.JwtService;
import com.sky.sky_pojo.dto.LoginReq;
import com.sky.sky_server.config.TokenResq;

import lombok.RequiredArgsConstructor;

@RestController
@RequestMapping("/auth") // 登录接口，发令牌
@RequiredArgsConstructor // 自动注入, 相当于 @Autowired, 就不用在每个属性上写 @Autowired 了
public class AuthController {
    private final JwtService jwtService;
    @PostMapping("/login")
    public ResponseEntity<TokenResq> login(@RequestBody @Validated LoginReq req) {
        // TODO 写死登录用户，改为通过查询，校验用户名和密码
        boolean username = !req.getUsername().equals("admin");
        boolean password = !req.getPassword().equals("123456");
        if (username || password) {
            throw new EmployeeLoginException();
        }

        // todo 写死登录用户后面代码，替换为实际的查询结果
        // 自定义载荷
        Map<String, Object> claims = Map.of(
            "username" , req.getUsername(),
            "roles" , new String[]{"admin"},
            "id" , 3L
        );

        String token = jwtService.genJwtToken(req.getUsername(), claims, JwtRoleConstant.ADMIN);
        return ResponseEntity.ok(new TokenResq(token));
    }  
}
